import React, { useEffect, useRef, useContext, useState, useCallback, useMemo, useLayoutEffect } from 'react';
import { ActivityIndicator, Alert, Dimensions, FlatList, ImageBackground, InteractionManager, NativeEventEmitter, NativeModules, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { fetchBookmark } from '../util/HttpUtil';
import Loading from './Loading';
let resData = []
import axios from 'axios';
import { loadNames, saveAppConfig, saveName } from '../util/StorageUtil';
import Toast from 'react-native-root-toast';
const { NAManager } = NativeModules;
const NAManagerEmitter = new NativeEventEmitter(NAManager);
const NAModule = NativeModules.NAModule;

const width = Dimensions.get('window').width
export class NameList extends React.Component {
    // const[isFirstFetch, setIsFirstFetch] = useState(false)
    // const [fetchCount, setFetchCount] = useState(0)
    count = 0
    names = []
    state = {
        result: [], isFetching: true, isErr: false
    }
    task_id
    isVideoRewardSuccess = false
    componentDidMount() {

        
        NAModule.loadVideoAd()
        

        
        this.subscription = NAManagerEmitter.addListener(
            "ENVENT_REQUEST_DATA",
            (data) => {

               console.log('DATA',data)
               this.isVideoRewardSuccess = data.isVideoRewardSuccess

               if(this.isVideoRewardSuccess){
                
               }
                
            }
        );

        InteractionManager.runAfterInteractions(() => {
            this.body = this.props.route.params

            loadNames().then((res) => {
                console.log('loadNames', res);
                if (res) {

                    this.names = res
                    this.body.nameList = this.names
                    console.log(this.body)
                    // this.count = 0
                    this.fetchAllData()
                }

                // this.
            })

        });

        // this.fetchData(this.body)
        // this.fetchData(this.body)
        // this.fetchData(this.body)
    }
    componentWillUnmount() {
        this._clearInterval()
        this.subscription&&this.subscription.remove()
    }
    _clearInterval = () => {
        this.timer && clearInterval(this.timer)
    }
    fetchAllData = () => {
        this.setState({ isFetching: true, isErr: false })

        if (this.body) {
            if (this.task_id) {
                this.fetchData({ task_id: this.task_id })
            } else {
                this.fetchTaskIdData()
            }
        }
        this.timer = setInterval(() => {
            if (this.body) {

                if (this.task_id) {
                    this.fetchData({ task_id: this.task_id })
                } else {
                    this.fetchTaskIdData()
                }
            }
        }, 30000);


    }

    fetchTaskIdData = () => {
        // console.log('this.body', this.body);
        this.body.jy = ""
        fetch('https://ai.wenxinyiyan.date/api/CreateName', {
            Interval: 300000,
            method: 'POST',
            headers: { "content-type": "application/json" },
            body: JSON.stringify(this.body),
        }).then((response) => {
            return response.json()
        }).then((responseData) => {
            // console.log("fetchTaskIdData", responseData);
            if (responseData.code == 200 && responseData.data?.task_id) {
                this.task_id = responseData.data?.task_id

                this.fetchData({ task_id: this.task_id })
            } else {
                this.setState({ isFetching: false, isErr: true })
                this.task_id = null

            }

        }).catch((error) => {
            this._clearInterval()
            this.setState({ isFetching: false, isErr: true })
            this.task_id = null
            console.warn("fetchTaskIdData error", error)
        }).finally(() => {
            // always executed
        });
    }
    fetchData = (body) => {
        if (body) {

            fetch('https://ai.wenxinyiyan.date/api/QueryTask', {
                Interval: 300000,
                method: 'POST',
                headers: { "content-type": "application/json" },
                body: JSON.stringify(body),
            }).then((response) => {
                return response.json()
            }).then((responseData) => {
                // console.log("fetchData", responseData)
                if (responseData.code == 200) {
                    let res = responseData.data?.result
                    let name = responseData.data?.name
                    if (name && name != "" && res && res != "") {

                        let r = []
                        if (this.state.result) {
                            r = [...this.state.result]
                        }

                        r.push({ xm: name, jx: res })

                        if (this.names.length > 10) {
                            this.names.shift()
                        }
                        this.names.push(name)
                        this.body.nameList = this.names
                        saveName(this.names)
                        this.setState({ result: r, isFetching: false, isErr: false })
                        // this.isVideoRewardSuccess = false
                        this._clearInterval()
                        this.task_id = null
                    } else {

                    }

                } else {
                    this.setState({ isFetching: false, isErr: true })
                    this.task_id = null
                    this._clearInterval()
                }



            })
                .catch((error) => {
                    this._clearInterval()
                    // this.count++
                    // if (this.count > 2) {
                    //     this.setState({ isFetching: false, isErr: true })
                    // } else {
                    //     // this.setState({ isErr: true })
                    // }
                    this.setState({ isFetching: false, isErr: true })
                    this.task_id = null
                    console.warn("fetchData error", error)
                })
                .finally(function () {
                    // always executed
                });


        }
        // console.warn("props.route", props.route)
    }

    getDesc = (desc) => {
        if (desc && desc.indexOf('\n\n') != -1) {
            desc = desc.substring(desc.indexOf('\n\n'))
            desc = desc.replace(/\n\n/, '\n')
            return desc.substring(desc.indexOf(''))
        }
        return null
    }


    render() {
        return (
            <SafeAreaView style={{ flex: 1 }}>
                <ImageBackground style={{ flex: 1, opacity: 0.2, position: 'absolute', width: '100%', height: '100%' }} source={require('../../img/b1.jpg')}>

                </ImageBackground>

                <TouchableOpacity
                    style={{ padding: 10, position: 'relative', left: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'flex-start', alignSelf: 'flex-start' }}
                    onPress={() => {
                        this.props.navigation.goBack()
                    }}>
                    <Ionicons name="chevron-back-outline" size={28} color={'#262626'} />
                </TouchableOpacity>

                <FlatList
                    contentContainerStyle={{ paddingBottom: 30 }}
                    ListFooterComponent={() => (
                        <View style={{ width: width, justifyContent: 'center', alignItems: 'center' }}>
                            {/* {this.state.result.length === 0 ?
                                    <><Loading style={{ padding: 10 }} animating={this.state.isFetching} />
                                        <Text style={{ fontSize: 14 }}>正在生成名字，请稍等</Text></> : null} */}
                            {this.state.isFetching ?
                                <><Loading style={{ padding: 10 }} animating={this.state.isFetching} />
                                    <Text style={{ fontSize: 16 }}>正在为您起名</Text>
                                    <Text style={{ fontSize: 12, color: '#999', marginTop: 5 }}>大约需要1至3分钟</Text></>
                                :
                                <Text onPress={() => {
                                    this.isVideoRewardSuccess = false
                                    NAModule.loadVideoAd()
                                    // this.fetchAllData()
                                    // Toast.show("加载广告中")
                                    
                                    this.fetchAllData()
                                    
                                }} style={{ color: 'tomato', fontSize: 16 }}>继续获取更多名字</Text>}

                            {this.state.isErr ?
                                <TouchableOpacity
                                    onPress={() => { this.fetchAllData() }}>
                                    <Text style={{ fontSize: 16 }}>网络错误，点击重试</Text></TouchableOpacity> : null}

                        </View>
                    )}

                    // contentContainerStyle={{justifyContent:'center',}}
                    // getItemLayout={(data, index) => (
                    //     { length: 50, offset: 50 * index, index }
                    // )}
                    renderItem={({ item, index }) => (
                        <TouchableOpacity
                            onPress={() => {
                                this.props.navigation.navigate("NameDetail", { item })

                            }}
                            style={{ justifyContent: 'space-between', alignItems: 'center', flexDirection: 'row', width: "96%", padding: 14, marginVertical: 5, marginHorizontal: 'auto' }}>
                            <Text style={{ fontSize: 20 }}>{item?.xm}</Text>
                            <View style={{flexDirection:'row',alignItems:'center'}}>
                                <Text style={{color:'#666',paddingEnd:10}}>点击查看解析</Text>
                                <Ionicons name="chevron-forward-outline" size={20} color={'#666'} />

                            </View>
                            {/* <Text numberOfLines={5}>{this.getDesc(item?.jx)}</Text> */}
                        </TouchableOpacity>
                    )}
                    data={this.state.result ? this.state.result : []} />
                {/* <ScrollView>
                        <Text>{result?.jx}</Text>
                    </ScrollView> */}
            </SafeAreaView>


        )
    }
}

/*
接口地址: /api/CreateName
请求方式: POST
请求参数:

    {
        "x": "张",                       //姓
        "xb": "男",                      //性别
        "csrq": "1990-01-01",           //出生日期
        "csdd": "北京",                   //出生地点
        "jy": "学习",                 //寄语
        "zs": 2,                        //生成名字个数
        "nameList": ["张三","李四"]      //已有名字列表
    }

返回参数:

    {
        "code": 200,
        "msg": "请求成功",
        "data": {
            "status": 0,                //0:成功 1:已存在
            "task_id": "xxxxx",         //任务id
            "msg": "请求成功"
        }
    }
*/
/*
接口地址: /api/QueryTask
请求方式: POST
请求参数:

    {
        "task_id": "xxxxx",     //任务id
    }

返回参数:

    {
        "code": 200,
        "msg": "请求成功",
        "data": {
            "task_status": 0,       //0:不存在 1:等待执行 2:正在执行 3:执行完成 4:执行出错
            "result": "xxxxx",      //生成的解析
            "msg": "任务不存在",
            "name": "张三",           //生成的名字
            "created_at": "2020-01-01 00:00:00",    //任务创建时间
            "updated_at": "2020-01-01 00:00:00" //任务更新时间
        }
    }
*/